<template>
<h1>{{weibo.nickname}}:{{weibo.content}}</h1>
  <p>发布于:{{weibo.created}}</p>
  <hr>
  <el-input v-model="comment.content"
            placeholder="说点儿啥..."></el-input>
  <el-button type="primary" @click="post()">发评论</el-button>
  <div v-for="c in arr">
    <h4>{{c.nickname}}评论说:{{c.content}}</h4>
    <span>发布于:{{c.created}}</span>
  </div>

</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import router from "@/router";
import qs from "qs";
import {ElMessage} from "element-plus";
const comment = ref({content:''});
const post = ()=>{
  let user = localStorage.user?JSON.parse(localStorage.user):null;
  if (user==null){
    alert("请先登录!");
    router.push('/login');
    return;
  }
  comment.value.userId = user.id; //设置作者
  comment.value.weiboId = weibo.value.id; //设置评论原微博
  //把对象转成查询字符串格式
  let data = qs.stringify(comment.value);
  axios.post('http://localhost:8080/v1/comments/add-new',data)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success("评论完成!");
      loadComments(weibo.value.id);
    }
  })

}

const weibo = ref({});
const arr = ref([]);
const loadComments = (id)=>{
  axios.get('http://localhost:8080/v1/comments/'+id)
  .then((response)=>{
    if (response.data.code==2001){
      arr.value = response.data.data;
    }
  })
}
onMounted(()=>{

  //得到地址栏中的id
  let id = new URLSearchParams(location.search).get('id');
  loadComments(id);
  //发请求获取详情数据
  axios.get('http://localhost:8080/v1/weibos/'+id+'/detail')
  .then((response)=>{
    if (response.data.code==2001){
      weibo.value = response.data.data;
    }
  })
})
</script>

<style scoped>

</style>